import {reactive, ref} from 'vue'
import {loginApi} from '@/api'
import { validateForm } from '@/utils/validateForm'
export function useLoginData() {
    const loading = ref(false)
    const loginFormRef = ref(null)
    const loginForm = reactive({
        username: 'Jery',
        password: '123456'
    })
    const pwdState = reactive({
        icon: 'eye-fill',
        type: 'password'
    })
    const handleToRegister = () => {
        uni.navigateTo({
            url: '/pages/register/register'
        })
    }

    function handleToLogin() {
        validateForm(loginFormRef, login)
    }

    function login() {
        loading.value = true
        loginApi(loginForm).then(res => {
           uni.setStorageSync('token', res.token)
           uni.setStorageSync('userInfo', JSON.stringify(res))
           uni.switchTab({ url: '/pages/index/index' })
        }).finally(_ => {
            loading.value = false
        })
    }

    function handlePwdInput() {
        pwdState.type = pwdState.type === 'text' ? 'password' : 'text'
        pwdState.icon = pwdState.icon === 'eye-fill' ? 'eye-off' : 'eye-fill'
    }

    return {
        loginForm,
        handleToRegister,
        handleToLogin,
        loading,
        pwdState,
        handlePwdInput,
        loginFormRef
    }
}